#!/bin/bash

wd=$(dirname $0)

function usage {
 cat<<EOF>&2
Usage

  $0 [-r] target

Description

  Generate one or more java source files into 'src/aino/lib' for the
  proc or arch described by 'target'.

Options

  -r|--r|--regenerate    Only regenerate existing files.

  -h|-?|--help           This message.

See also

 ${wd}/unport.sh         Drop generated 'src/aino/lib' files that fail 
                         to build.

EOF
 exit 1
}

target=${1}
opt=0
reg=0

while [ -n "${1}" ]
do
 case ${1} in
  -*r*)
    opt=1
    reg=1
    ;;
   -*[\?h]*)
    usage
    ;;
   *)
    if [ 0 -lt ${opt} ]
    then
     target=${1}

    elif [ "${target}" != "${1}" ]
    then
     usage 
    fi
    ;;
 esac
 shift
done

#
# portlist handles arch and proc targets
#
for proc in $(${wd}/portlist.sh ${target} )
do
  if clk=$(${wd}/clock.sh ${proc} )
  then
   if arch=$(${wd}/arch.sh ${proc} )
   then
    if [ 0 -lt ${reg} ]
    then

      if [ -f src/aino/lib/${proc}.java ]
      then
        if java -cp aino.jar aino.port.Main ${clk} ${arch} ${proc}
        then
         ls -l src/aino/lib/${proc}.java
        else
         break;
        fi
      fi

    elif java -cp aino.jar aino.port.Main ${clk} ${arch} ${proc}
    then
      if 2>/dev/null svn add src/aino/lib/${proc}.java
      then
       continue
      else
       ls -l src/aino/lib/${proc}.java
      fi
    fi
   fi
  fi
done
